<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="订单编号">
              <a-input v-model="queryParam.orderNo" placeholder="请输入订单编号" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="客户名称">
              <a-input v-model="queryParam.customerName" placeholder="请输入客户名称" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="项目名称">
              <a-input v-model="queryParam.projectName" placeholder="请输入项目名称" allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="订单状态">
              <a-select v-model="queryParam.status" placeholder="请选择订单状态" allow-clear>
                <a-select-option :value="0">待审核</a-select-option>
                <a-select-option :value="1">审核通过-待上传</a-select-option>
                <a-select-option :value="2">已上传汇总单-待上传优化单</a-select-option>
                <a-select-option :value="3">已上传优化单-待提交审核</a-select-option>
                <a-select-option :value="4">待下发</a-select-option>
                <a-select-option :value="5">领料单待审核</a-select-option>
                <a-select-option :value="6">待领料</a-select-option>
                <a-select-option :value="7">生产中</a-select-option>
                <a-select-option :value="8">已完成</a-select-option>
                <a-select-option :value="9">已驳回</a-select-option>
                <a-select-option :value="10">已入库</a-select-option>
                <a-select-option :value="11">已发货</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="订单日期">
              <a-range-picker
                v-model="queryParam.orderDateRange"
                format="YYYY-MM-DD"
                :placeholder="['开始日期', '结束日期']"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('半成品销售订单')">导出</a-button>
      <a-button type="primary" icon="import" @click="handleImportExcel">导入</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"> <a-icon type="delete" />删除 </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /> </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px" v-if="selectedRowKeys.length > 0">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{
          selectedRowKeys.length
        }}</a
        >项&nbsp;&nbsp;
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: 1400 }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <!-- 客户地址 -->
        <template slot="customerAddressSlot" slot-scope="text, record">
          <span>{{
            [record.customerProvince, record.customerCity, record.customerDistrict].filter(Boolean).join(' ')
          }}</span>
        </template>

        <!-- 工程地址 -->
        <template slot="projectAddressSlot" slot-scope="text, record">
          <span>{{
            [record.projectProvince, record.projectCity, record.projectDistrict].filter(Boolean).join(' ')
          }}</span>
        </template>

        <!-- 操作按钮 -->
        <template slot="action" slot-scope="text, record">
          <!-- 编辑按钮，仅当订单状态为0（待审核）时显示 -->
          <template v-if="record.status === 0 || record.status === '0'">
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleAudit(record)">审核</a>
            <a-divider type="vertical" />
          </template>
          <!-- 下发按钮，仅当订单状态为1（审核通过）时显示 -->
          <template v-if="record.status === 1 || record.status === '1'">
            <a @click="handleDispatch(record)">下发</a>
            <a-divider type="vertical" />
          </template>
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </a-table>
    </div>

    <!-- 表单区域 -->
    <semi-product-sales-order-modal ref="modalForm" @ok="modalFormOk"></semi-product-sales-order-modal>
    <!-- 详情区域 -->
    <semi-product-sales-order-detail ref="detailModal"></semi-product-sales-order-detail>
    <!-- 审核弹窗 -->
    <audit-modal ref="auditModal" @ok="auditModalOk"></audit-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import SemiProductSalesOrderModal from './modules/SemiProductSalesOrderModal'
import SemiProductSalesOrderDetail from './modules/SemiProductSalesOrderDetail'
import AuditModal from './modules/AuditModal'
import {
  submitSemiProductSalesOrder,
  cancelSemiProductSalesOrder,
  completeSemiProductSalesOrder,
} from '@/api/oms/semiProductSalesOrder'
import { filterObj } from '@/utils/util'

export default {
  name: 'SemiProductSalesOrderList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    SemiProductSalesOrderModal,
    SemiProductSalesOrderDetail,
    AuditModal,
  },
  data() {
    return {
      description: '半成品销售订单管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '订单编号',
          align: 'center',
          width: 150,
          dataIndex: 'orderNo',
        },
        {
          title: '客户名称',
          align: 'center',
          width: 150,
          dataIndex: 'customerName',
        },
        {
          title: '项目名称',
          align: 'center',
          width: 150,
          dataIndex: 'projectName',
        },
        {
          title: '客户地址',
          align: 'center',
          dataIndex: 'customerAddress',
          width: 150,
          ellipsis: true,
          scopedSlots: { customRender: 'customerAddressSlot' },
        },
        {
          title: '工程地址',
          align: 'center',
          dataIndex: 'projectAddress',
          width: 150,
          ellipsis: true,
          scopedSlots: { customRender: 'projectAddressSlot' },
        },
        {
          title: '订单日期',
          align: 'center',
          width: 150,
          dataIndex: 'orderDate',
        },
        {
          title: '交货日期',
          align: 'center',
          dataIndex: 'deliveryDate',
          width: 150,
        },
        {
          title: '订单金额',
          align: 'center',
          dataIndex: 'totalAmount',
          customRender: function (text) {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
          width: 150,
        },
        {
          title: '已付金额',
          align: 'center',
          dataIndex: 'paidAmount',
          customRender: function (text) {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
          width: 150,
        },
        {
          title: '订单状态',
          align: 'center',
          dataIndex: 'status',
          customRender: function (text) {
            const statusMap = {
              0: '待审核',
              1: '审核通过',
              2: '已上传汇总单-待上传优化单',
              3: '已上传优化单-待提交审核',
              4: '待下发',
              5: '领料单待审核',
              6: '待领料',
              7: '生产中',
              8: '已完成',
              9: '已驳回',
              10: '已入库',
              11: '已发货',
            }
            return statusMap[text] || '未知状态'
          },
          width: 150,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 200,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/oms/semiProductSalesOrder/list',
        delete: '/oms/semiProductSalesOrder/delete',
        deleteBatch: '/oms/semiProductSalesOrder/deleteBatch',
        exportXlsUrl: 'oms/semiProductSalesOrder/exportXls',
        importExcelUrl: 'oms/semiProductSalesOrder/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
      selectedRowKeys: [],
    }
  },
  created() {
    this.getSuperFieldList()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'orderNo', text: '订单编号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'customerName', text: '客户名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'projectName', text: '项目名称', dictCode: '' })
      fieldList.push({ type: 'int', value: 'status', text: '订单状态', dictCode: '' })
      fieldList.push({ type: 'date', value: 'orderDate', text: '订单日期', dictCode: '' })
      this.superFieldList = fieldList
    },
    handleAdd: function () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增半成品销售订单'
    },
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑半成品销售订单'
    },
    handleDetail: function (record) {
      this.$refs.detailModal.showDetail(record)
    },
    handleProgress: function (record) {
      this.$refs.progressModal.showProgress(record)
    },
    handleTransaction: function (record) {
      this.$refs.transactionModal.showTransaction(record)
    },
    handleAudit: function (record) {
      this.$refs.auditModal.showAudit(record)
    },
    handleDispatch: function (record) {
      const that = this
      this.$confirm({
        title: '确认操作',
        content: '确定要下发此订单吗？',
        onOk: function () {
          // 这里可以调用下发订单的API
          that.$message.success('订单下发成功')
          that.loadData()
        },
      })
    },
    handleSubmit: function (record) {
      const that = this
      this.$confirm({
        title: '确认操作',
        content: '确定要提交审核吗？',
        onOk: function () {
          submitSemiProductSalesOrder(record.id).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    handleCancel: function (record) {
      const that = this
      this.$prompt({
        title: '取消订单',
        content: '请输入取消原因：',
        onOk: function (value) {
          if (!value) {
            that.$message.warning('请输入取消原因')
            return
          }
          cancelSemiProductSalesOrder(record.id, value).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    handleComplete: function (record) {
      const that = this
      this.$confirm({
        title: '确认操作',
        content: '确定要完成订单吗？',
        onOk: function () {
          completeSemiProductSalesOrder(record.id).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        },
      })
    },
    auditModalOk: function () {
      this.loadData()
    },
    getQueryParams() {
      // 获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize

      // 处理日期范围查询
      if (this.queryParam.orderDateRange && this.queryParam.orderDateRange.length === 2) {
        param.orderDate_begin = this.queryParam.orderDateRange[0].format('YYYY-MM-DD')
        param.orderDate_end = this.queryParam.orderDateRange[1].format('YYYY-MM-DD')
        delete param.orderDateRange
      }

      return filterObj(param)
    },
    getQueryField() {
      // TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
